<template>
  <div class="detail">
    <div class="content">
      <div class="info" style="background-color: #FFFFFF">
        <van-row class="custom-row" justify="center" align="center">
          <van-col span="5">
            <van-image class="contact-headimgurl" round width="60" height="60" :src="dataInfo.headimgurl ? dataInfo.headimgurl : generateAvatar(dataInfo.name)" />
          </van-col>
          <van-col span="19">
            <div class="contact-info">
              <div class="contact-name">
                <span>{{ dataInfo.name }}</span>
              </div>
              <div class="contact-tag">
                <van-tag type="primary" style="margin-right: 10px">{{dataInfo.leads_phase}}</van-tag>
                <van-tag type="warning" plain style="margin-right: 10px" v-if="dataInfo.leads_status">{{dataInfo.leads_status}}</van-tag>
              </div>
              <div class="contact-source">
                留资来源：{{ dataInfo.source }}
              </div>
            </div>
          </van-col>
        </van-row>
      </div>
      <div class="field">
        <van-cell-group>
          <template #title>
            <span style="font-size: 16px;font-weight: bold">核心资料</span>
          </template>
          <van-cell v-for="(value,key) in dataInfo.basic_info" :key="key">
            <template #title>
              <span style="color:#666666">{{ infoMap[key] || key }}</span>
            </template>
            <template #value>
              <span>{{ value }}</span>
            </template>
          </van-cell>

        </van-cell-group>
        <van-cell-group>
          <template #title>
            <span style="font-size: 16px;font-weight: bold">潜客资料</span>
          </template>
          <van-cell v-for="item in dataInfo.fields.slice(0, numSliceField)" :key="item.id">
            <template #title>
              <span style="color:#666666">{{item.name}}</span>
            </template>
            <template #value>
              <span @click="fieldEdit(item)">{{item.value}}</span>
            </template>
          </van-cell>
          <div class="no-more">
            <span v-if="dataInfo.fields.length > numShowField" @click="toggleField">
              {{ fieldExpanded ? '收起' : '点击查看更多' }}
              <span>
                <van-icon :name="fieldExpanded ? 'arrow-up':'arrow-down'" />
              </span>
            </span>
            <span v-else>没有更多数据</span>
          </div>

        </van-cell-group>
      </div>
      <div class="tag">
        <van-cell-group>
          <template #title>
            <span style="font-size: 16px;font-weight: bold">潜客标签</span>
          </template>
          <div v-if="dataInfo.tags.length > 0" style="padding:10px 20px">
            <van-space wrap size="12px">
              <van-tag size="medium" type="primary" plain v-for="item in dataInfo.tags.slice(0, numSliceTag)" :key="item.id">
                {{item.name}}
              </van-tag>
            </van-space>
          </div>
          <div class="no-more">
            <span v-if="dataInfo.tags.length > numShowTag" @click="toggleTag">
              {{ tagExpanded ? '收起' : '点击查看更多' }}
               <span>
                <van-icon :name="tagExpanded ? 'arrow-up':'arrow-down'" />
              </span>
            </span>
            <span v-else>没有更多数据</span>
          </div>

        </van-cell-group>
      </div>
      <div class="actionRecord">
        <van-cell-group>
          <template #title>
            <div class="flex justify-between">
              <span style="font-size: 16px;font-weight: bold">潜客日志</span>
              <span style="color: #3b8cff" @click="showRecord">更多<van-icon color="#3b8cff" name="arrow" /></span>
            </div>
          </template>
          <LeadsRecord :sale_uuid="omniUserUuid" :leads_uuid="uuid" type="one"></LeadsRecord>
        </van-cell-group>
      </div>
    </div>


    <div class="bottom">

      <div v-if="dataInfo.assign_sale_uuid">
        <van-action-bar>
          <van-action-bar-icon icon="phone-o" text="电话" @click="call" />
          <van-action-bar-icon icon="records-o" text="备注" @click="addRemark" />
          <van-action-bar-icon icon="share-o" text="分配" @click="assign" />
          <van-action-bar-button type="primary" text="更新状态" @click="updateStatus" />
        </van-action-bar>

        <van-action-sheet v-model:show="statusShow" title="更新潜客状态">
          <div class="statusContent" style="padding:10px 10px 30px 10px">
            <van-row :gutter="[10, 20]" justify="space-between">
              <van-col v-for="(item,index) in statusArr" :key="index" span="12" class="centered-col">
                <van-button :type="item.id === selectStatusData.id ? 'primary' : 'default'" style="width:100%" plain @click="selectStatus(item)">{{ item.text }}</van-button>
              </van-col>
            </van-row>
          </div>
        </van-action-sheet>
        <van-action-sheet v-model:show="statusUpdateConfirm" title="确认状态变更">
          <div class="statusContent" style="padding:10px 10px 30px 10px">
            <div class="confirmContent" style="display: flex;flex-direction: column;font-size:14px">
              <div class="confirmStatus" style="display: flex;justify-content: space-between; background-color: #F8F8F8;padding:10px">
                <span>潜客状态更新为：<span style="color:#3b8cff">{{selectStatusData.text}}</span></span>
                <span style="color:#3b8cff" @click="goBackStatus()">重新选择</span>
              </div>
              <div class="confirmRemark">
                <van-cell-group inset>
                  <van-field
                      v-model="confirmData.content"
                      rows="4"
                      autosize
                      clearable
                      label=""
                      type="textarea"
                      maxlength="255"
                      label-align="top"
                      placeholder="请输入备注"
                      show-word-limit
                  />
                  <van-divider />
                </van-cell-group>
              </div>

              <div class="remarkTemplate" v-if="selectStatusData.children && selectStatusData.children.length>0" style="max-height: 180px; overflow-y: auto;">
                <van-cell-group title="备注模版">
                  <van-list>
                    <van-cell v-for="item in selectStatusData.children" :key="item.id" :title="item.text" >
                      <template #right-icon>
                        <van-icon name="add-o" color="#1989fa" @click="copyTemplate(item.text)" style="font-size: 22px;line-height: inherit;"/>
                      </template>
                    </van-cell>
                  </van-list>
                </van-cell-group>
              </div>
              <div style="padding: 10px">
                <van-button type="primary" block @click="saveStatusRemark">保存</van-button>
              </div>
            </div>
          </div>
        </van-action-sheet>
        <van-action-sheet v-model:show="remarkUpdateConfirm" title="写备注">
          <div class="statusContent" style="padding:10px 10px 30px 10px">
            <div class="confirmContent flex flex-col" style="font-size:14px">
              <div class="confirmRemark">
                <van-cell-group inset>
                  <van-field
                      v-model="remarkContent"
                      rows="4"
                      autosize
                      clearable
                      label=""
                      type="textarea"
                      maxlength="255"
                      label-align="top"
                      placeholder="请输入备注"
                      show-word-limit
                  />
                  <van-divider />
                </van-cell-group>
              </div>

              <div class="remarkTemplate" v-if="remarkArr.length>0" style="max-height: 180px; overflow-y: auto;">
                <van-cell-group title="备注模版">
                  <van-list>
                    <van-cell v-for="item in remarkArr" :key="item.id" :title="item.text" >
                      <template #right-icon>
                        <van-icon name="add-o" color="#1989fa" @click="copyRemark(item.text)" style="font-size: 22px;line-height: inherit;"/>
                      </template>
                    </van-cell>
                  </van-list>
                </van-cell-group>
              </div>
              <div style="padding: 10px">
                <van-button type="primary" :disabled="!isRemarkValid" block @click="saveRemark">保存</van-button>
              </div>
            </div>
          </div>
        </van-action-sheet>
      </div>
      <div v-else>
        <van-tabbar v-if="dataInfo.uuid" active-color="#ee0a24" class="flex items-center justify-center">
          <van-button class="p-2" type="primary" block @click.stop="assignLeads(dataInfo.uuid)">跟进</van-button>
        </van-tabbar>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, watch, ref,computed} from 'vue'
import {
  LeadsShow,
  LeadsInfoType,
  StatusList,
  StatusLeads,
  StatusUpdate,
  StatusUpdateDataType,
  RemarkUpdate, LeadsAssign
} from "@/api/leads.ts";
import {useRoute, useRouter} from "vue-router";
import { generateAvatar } from '@/utils/avatar'
// import {useUserStore} from "@/stores/userStore.ts";
import { LeadsRecord} from '@/views/components/leads';
//user uuid
const route = useRoute();
const router = useRouter();
const uuid = route.params.uuid as string;
const customerUuid = route.params.customerUuid;

const dataInfo = ref<LeadsInfoType>({
  assign_sale_uuid: "",
  basic_info: {
    name:"",
    mobile:"",
    company:"",
    email:"",
    position:""
  },
  fields: [],
  headimgurl: "",
  leads_phase: "",
  leads_status: "",
  leads_status_uuid: "",
  mobile: "",
  name: "",
  record: [],
  source: "",
  tags: [],
  uuid: ""
})

const infoMap = {
  name: "姓名",
  mobile: "手机号",
  email: "邮箱",
  company: "公司",
  position: "职位"
};

//const store = useUserStore();
//const assignSaleUuid = computed(() => store.user?.omni_user_uuid as string);
const omniUserUuid = localStorage.getItem('omni_user_uuid') as string;

onMounted(() => {
  getLeadsInfo(uuid)
});

const getLeadsInfo=(uuid:string)=>{
  try {
    LeadsShow(uuid).then((response) => {
      dataInfo.value = response.data
      dataInfo.value.record = [
        {name:"提交表单",date:"2024-10-01 00:00:01"},
        {name:"提交表单",date:"2024-10-01 00:00:01"},
        {name:"提交表单",date:"2024-10-01 00:00:01"},
        {name:"提交表单",date:"2024-10-01 00:00:01"},
        {name:"提交表单",date:"2024-10-01 00:00:01"},
      ]
    })
  } catch (e) {
    console.log(e);
  } finally {

  }
}


const showRecord = () =>{
  router.push(`/dist/${customerUuid}/leadsRecord/${uuid}`);
}


const statusArr = ref<StatusLeads[]>([]);
const selectStatusData = ref<StatusLeads>({
  id:'',
  text:'',
  children:[]
});
const selectStatus=(item:StatusLeads)=>{
  statusUpdateConfirm.value = true
  statusShow.value = false;
  selectStatusData.value = item
}
const queryStatus=()=>{
  if(statusArr.value.length < 1){
    try {
      StatusList(false).then((response) => {
        statusArr.value = response.data
        //用户的当前状态，对应的备注模版
        if(dataInfo.value.leads_status_uuid){
          for (const node of statusArr.value) {
            if (node.id === dataInfo.value.leads_status_uuid) {
              remarkArr.value = node.children
              break
            }
          }
        }
      })
    } catch (e) {
      console.log(e);
    } finally {

    }
  }
}

const assign=()=>{

}


const fieldEdit=(obj:any): void=>{
  console.log(obj)
}


/** 资料 **/
const fieldExpanded = ref(false)
const numShowField = 4
const numSliceField = ref(numShowField)
const toggleField = ()=>{
  fieldExpanded.value = !fieldExpanded.value;
  numSliceField.value = fieldExpanded.value ? 999 : numShowField;
}


/** 标签 **/
const tagExpanded = ref(false)
const numShowTag = 20
const numSliceTag = ref(numShowTag)
const toggleTag = ()=>{
  tagExpanded.value = !tagExpanded.value;
  numSliceTag.value = tagExpanded.value ? 999 : numShowTag;
}




const statusShow = ref(false);


const updateStatus=()=>{
  queryStatus()
  statusShow.value = true;
}

const statusUpdateConfirm = ref(false);


const confirmData = ref<StatusUpdateDataType>({
  sale_uuid:omniUserUuid,
  uuid:'',
  content:''
})
watch(() => selectStatusData.value.id, (newId) => {
  confirmData.value.uuid = newId;
});

const goBackStatus = ()=>{
  statusShow.value = true;
  statusUpdateConfirm.value = false
}

const copyTemplate = (content:any)=>{
  confirmData.value.content = content
}
//电话联系
const call = () =>{
  window.location.href = `tel:${dataInfo.value.mobile}`;
}

//添加备注
const addRemark = () =>{
  queryStatus()
  remarkUpdateConfirm.value = true
}
const remarkContent = ref("");
const remarkUpdateConfirm = ref(false);
const remarkArr = ref<StatusLeads[]>([])
const copyRemark = (content:string)=>{
  remarkContent.value = content
}
const saveRemark = ()=>{
  try {
    RemarkUpdate(uuid,{
      sale_uuid:omniUserUuid,
      content:remarkContent.value
    }).then((response) => {
      console.log(response.data)
      getLeadsInfo(uuid)
    })
  } catch (e) {
    console.log(e);
  } finally {
    remarkUpdateConfirm.value = false
  }
}
const isRemarkValid = computed(() => {
  return remarkContent.value.trim().length > 0;
});

const saveStatusRemark = ()=>{
  console.log(confirmData.value)
  statusRemarkUpdate()
  
}
const statusRemarkUpdate=()=>{
  try {
      StatusUpdate(uuid,confirmData.value).then((response) => {
        console.log(response.data)
        getLeadsInfo(uuid)
      })
    } catch (e) {
      console.log(e);
    } finally {
      statusUpdateConfirm.value = false
    }
}


const assignLeads = (uuid:string): void => {
  if(omniUserUuid){
    try {
      LeadsAssign(uuid,{
        sale_uuid:omniUserUuid
      }).then((response) => {
        console.log(response.data)
        getLeadsInfo(uuid)
      })
    } catch (e) {
      console.log(e);
    }
  }
};



</script>

<style scoped>
.detail{
  background-color: #F8F8F8;
  min-height: 100Vh;
}
.content{
  padding-bottom: 60px; /* 适当的底部填充，确保内容不会被van-action-bar遮挡 */
}

.custom-row{
  padding:10px;
  font-size: 14px;
}


.contact-name {
  display: flex;
  align-items: center;
  font-size: 16px; /* 设置姓名字体大小 */
  margin-bottom: 10px;
}

.contact-name span {
  font-weight: bold;
}

.contact-tag {
  font-size: 10px; /* 设置标签字体大小 */
  padding: 2px 4px; /* 设置标签内边距 */
  height: auto;
  line-height: 12px; /* 设置标签行高 */
  margin-bottom: 8px;
}
.contact-source{
  color:#9D9D9D;
}


.no-more {
  text-align: center;
  color: #888;
  padding: 10px 0;
  font-size: 12px; /* 设置“没有更多了”字体大小 */
}
.centered-col {
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
